import axios from 'axios'
import webMap from './map.web'
// 鉴权过就不需要再鉴权了
let feishuConfiged = false
// 飞书app环境中定位
class Location_feishu {
  getAddress(callback) {
    let corpCode = sessionStorage.getItem('feishu_corp')
    if (!corpCode) {
      new webMap().getAddress(callback)
      // callback({code: -1, msg: '暂无飞书定义编码'})
      return
    }
    if (feishuConfiged) {
      this.getLocation(callback)
      return
    }
    let that = this
    axios.get('/auth/getAuthConfig.json', {
      params: {
        corp: corpCode,
        url: window.location.href,
        client: 'feishu'
      }
    }).then(res => {
      let rs = res.data
      let data = rs.data
      if (rs.code != '0' || !data || !data.signature) {
        callback({code: -1, msg: '无法获得鉴权信息'})
        return
      }
      window.h5sdk.config({
        appId: data.appId, // 必填，应用ID
        timestamp: data.timeStamp, // 必填，生成签名的时间戳
        nonceStr: data.nonceStr, // 必填，生成签名的随机串
        signature: data.signature, // 必填，签名
        jsApiList: [
          // 'device.geolocation.get'
        ], // 必填，需要使用的jsapi列表。
        onSuccess: function(result) {
          // 成功回调，可以在成功之后使用 tt.xx jsapi
          console.log('飞书鉴权成功456')
          // feishuConfiged = true
          that.getLocation(callback)
        },
        onFail: function(res) {
          // 失败回调
          console.log('飞书鉴权失败123',res)
          callback({code: -1, msg: JSON.stringify(res)})
        }
      });
    })
  }
  getLocation(callback) {
    tt.getLocation({
      "type": "gcj02",
      "timeout": 5,
      "cacheTimeout": 20,
      "accuracy": "best",
      success(data) {
        data.from = 3
        Promise.resolve(data).then(webMap.geoconv).then(webMap.geocoder).then(res => {
          if ( res && res.status === 0) {
            const ret = res.result
            callback({
              province: ret.addressComponent.province,
              city: ret.addressComponent.city,
              district: ret.addressComponent.district,
              address: ret.formatted_address,
              lon: ret.location.lng,
              lat: ret.location.lat
            })
          }else{
            console.error('feishu获取位置出错!')
          }
        })
      },
      fail(res) {
        // alert(`getLocation fail: ${JSON.stringify(res)}`)
        console.log(`getLocation fail: ${JSON.stringify(res)}`);
        callback({code: -1, msg: JSON.stringify(res)})
      }
    })
  }
}
export default Location_feishu
